package com.itc.api.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.itc.api.mapper.UserMapper;
import com.itc.api.pojo.dao.User.UserDAO;
import com.itc.api.response.Result;
import com.itc.api.response.exception.ResultStatus;
import com.itc.api.service.UserService;
import com.itc.api.utils.JWTUtils;
import com.itc.api.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 登录
     *
     * @param account  账户
     * @param password 密码
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> login(String account, String password){
        log.info("account:{},password:{}", account, password);
        // 根据用户名
        UserDAO login = userMapper.selectByAccount(account);
        if (StrUtil.equals(password, login.getPassword())) {
            Map<String, Object> payload = new HashMap<>();
            payload.put("id", login.getUserId());
            payload.put("account", account);
            String token = JWTUtils.getToken(payload);
            String tokenKey = "login:token:" + token;
            redisUtils.set(tokenKey, payload, 60 * 60 * 24 * 7);
            log.info("token:{},登录token存储成功！", token);
            return Result.success(token);
        }
        return Result.failure(ResultStatus.FAIL, "登录失败");
    }

    /**
     * 验证
     *
     * @param token 令牌
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> verify(String token) {
        Object o = redisUtils.get("login:token:" + token);
        if (ObjectUtil.isEmpty(o)){
            return Result.failure(ResultStatus.FAIL, "token已失效");
        }
        return Result.success("身份校验通过");
    }

    /**
     * 注册
     *
     * @param email         电子邮件
     * @param account       账户
     * @param password      密码
     * @param authCode      身份验证代码
     * @param authCodeToken 验证码令牌
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> register(String email, String account, String password, String authCode, String authCodeToken) {
        return null;
    }

}